<template>
  <div class="app-container">

    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="主订单号:" prop="orderNo">
          <el-input v-model="queryParams.orderNo" clearable placeholder="请输入主订单号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车牌号:" prop="carNo">
          <el-input v-model="queryParams.carNo" clearable placeholder="请输入车牌号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="还车类别:" prop="returnCategoryList">
          <el-select v-model="queryParams.returnCategoryList" multiple placeholder="请选择工单状态">
            <el-option v-for="item in dict.type.return_car_type" :label="item.label" :value="item.value"
                       :key="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="还车时间:">
          <el-date-picker v-model="dateTime" type="daterange" range-separator="-" start-placeholder="开始日期"
                          end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable @change="changeDateTime"/>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="退保状态:" prop="refundStatusList">
          <el-select v-model="queryParams.refundStatusList" multiple placeholder="请选择工单状态">
            <el-option v-for="item in dict.type.refund_status" :label="item.label" :value="item.value"
                       :key="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="财务状态:" prop="financeStatus">
          <el-select v-model="queryParams.financeStatus" placeholder="请选择工单状态">
            <el-option v-for="item in dict.type.finance_status" :label="item.label" :value="item.value"
                       :key="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="客户名称:" prop="customerName">
          <el-input v-model="queryParams.customerName" clearable placeholder="请输入客户名称"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆归属:">
          <el-select filterable v-model="queryParams.ascriptionId" clearable placeholder="请选择车辆归属"
                     style="width: 100%">

            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId"/>

          </el-select>
        </el-form-item>
      </el-col>

    </SearchContent>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">

        <e-button type="primary" size="mini" v-hasPermi="['returnMargin:index:batch']"
                  :disabled="idList.length === 0"
                  @click="handleBatch">
          合并退保
        </e-button>
        <e-button type="primary" size="mini" v-hasPermi="['returnMargin:index:derive']" @click="handleDerive">导出
        </e-button>

      </div>
      <table-page :loading="loading" :dataList="dataList" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @setSizeCurrent="handleList" rowKey="returnCarDepositId"
                  ref="multipleTable"
                  @selectionChange="handleSelectionChange" border>

        <template slot="tableColAc">
          <el-table-column type="selection" :reserve-selection="true" width="55" align="center"
                           :selectable="checkSelectable"/>
          <el-table-column label="操作" align="center" :selectable="checkSelectable" fixed="left" width="100">
            <template #default="{row}">
              <el-button size="mini" type="text" v-hasPermi="['returnMargin:index:view']"
                         @click="handleView(row, 'view')">查看
              </el-button>

              <el-button size="mini" type="text"
                         v-if=" Number(row.refundStatus) === 0"
                         v-hasPermi="['returnMargin:index:work']" @click="handleWork(row)">退保
              </el-button>

            </template>
          </el-table-column>

        </template>

        <template slot="tableCol">
          <el-table-column align="center" label="主订单号" width="220">
            <template #default="{row}">
              <el-button type="text" class="enable-text-select" @click="handleTo(row.orderNo)"> {{
                  row.orderNo || '-'
                }}
              </el-button>
            </template>
          </el-table-column>

          <el-table-column align="center" label="批次号" width="220">
            <template #default="{row}">
              {{ row.pcNo || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="车牌号" min-width="100" prop="carNo">
            <template #default="{row}">
              {{ row.carNo || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="退保状态" width="130">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.refund_status, row.refundStatus) || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="审批状态" show-overflow-tooltip min-width="130">
            <template #default="{row}">
              {{ row.expenseStatus || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="财务状态" width="130">
            <template #default="{row}">
              {{ row.financeStatus == '0' ? '-' : selectDictLabel(dict.type.finance_status, row.financeStatus) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="所属公司" show-overflow-tooltip min-width="160" prop="ascription">
            <template #default="{row}">
              {{ row.companyName || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="客户名称" width="160" show-overflow-tooltip prop="customerName">
            <template #default="{row}">
              {{ row.customerName || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="还车时间" width="140">
            <template #default="{row}">
              {{ row.returnCarDate ? $dayjs(row.returnCarDate).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="还车类型" width="130">
            <template #default="{row}">
              {{ selectDictLabel(dict.type.return_car_type, row.returnCategory) || '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="欠租" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.rentArrears)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="尾款" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.balancePayment)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="车损费" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.vehicleDamageFee)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="加速折旧费" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.depreciation)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="违章费用" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.violationFee)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="违约金" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.defaultDeduction)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="超里程费" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.overMileageFee)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="其他扣款费用" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.otherFee)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="客户理赔款" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.compensationClaims)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="减免金额" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.exemptionAmount)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="保证金" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.deposit)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="是否使用保证金抵扣" width="150">
            <template #default="{row}">
              {{ row.deductionStatus === '0' ? '否' : row.deductionStatus === '1' ? '是' : '-' }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="应退金额" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.returnFee)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="补缴金额" width="130">
            <template #default="{row}">
              {{ (format_thousand(row.paymentFee)) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="申请人" width="130">
            <template #default="{row}">
              {{ row.applyName || '-' }}
            </template>
          </el-table-column>

        </template>
      </table-page>
    </div>

  </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import {listDept} from "@/api/system/dept";
import * as apis from "@/api/returnMargin";
import {OrderParam} from '@/api/finance/manage/collect/api.js';

export default {
  name: "ReturnMarginList", //还车退保证金列表
  dicts: ["return_car_type", "refund_status", "finance_status"],
  components: {
    SearchContent,
  },
  computed: {},
  watch: {},
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: "",
        returnCategoryList: [],
        returnStartDate: "",
        returnEndDate: "",
        refundStatusList: [],
        financeStatus: "",
        customerName: '',
      },
      dateTime: [],
      total: 0,
      loading: false,
      dataList: [],
      companyOriginList: [],
      orderNoList: [],
      idList: [],
      returnCategoryList: []
    };
  },
  created() {
    this.getCompanyOrigin();
    this.handleList();
  },
  activated() {
    this.handleList();
  },
  mounted() {
  },
  methods: {
    //主
    async handleTo(val) {
      if (!val) return
      try {
        let res = await OrderParam(val)
        if (res.code === 200) {
          this.$router.push({
            name: 'OrderDetails',
            query: {
              type: res.data.carType,
              beFrom: 'OrderView',
              orderId: res.data.orderId,
              preOrderId: res.data.preOrderId,
              calcSchemeId: res.data.calcSchemeId,
              isMenu: this.$route.query.isMenu,
            },
          })
        }
      } catch (e) {
        console.error(e)
      }
    },

    getCompanyOrigin() {
      listDept({
        deptType: "2", //组织类型（1部门 2公司）
        regionId: null, //所在城市（省市区id）
      }).then((res) => {
        this.companyOriginList = res.data;
      });
    },

    changeDateTime(val) {
      if (val) {
        this.queryParams.returnStartDate = val[0]
        this.queryParams.returnEndDate = val[1]
      }
    },

    async handleList() {
      this.loading = true;
      try {
        let res = await apis?.queryPageList(this.queryParams);
        let {rows, total} = res;
        this.dataList = rows
        this.total = total;
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;
      }
    },

    handleSelectionChange(val) {
      this.orderNoList = val.map(item => {
        return item.orderNo
      })
      this.idList = val.map(item => {
        return item.returnCarDepositId
      })
      this.returnCategoryList = val.map(item => {
        return item.returnCategory
      })
    },

    checkSelectable(row) {
      if (Number(row.refundStatus) === 0) {
        return true
      } else {
        return false
      }

    },

    handleView(row) {
      if (row.isPc === true) {
        this._toPage({
          path: "/ReturnCar/ReturnMarginMerge",
          name: "ReturnMarginMerge",
          query: {
            id: row.returnCarDepositId,
            flowId: row.flowId,
            type: 'view'
          }
        });
      }
      if (row.isPc === false) {
        this._toPage({
          path: "/ReturnCar/ReturnMarginDetails",
          name: "ReturnMarginDetails",
          query: {
            id: row.returnCarDepositId,
            flowId: row.flowId
          }
        });
      }

    },

    handleWork(row) {
      this._toPage({
        path: "/ReturnCar/ReturnMarginInsurance",
        name: "ReturnMarginInsurance",
        query: {
          id: row.returnCarDepositId
        }
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.handleList();
    },

    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderNo: "",
        returnCategoryList: [],
        returnStartDate: "",
        returnEndDate: "",
        refundStatusList: [],
        financeStatus: "",
        customerName: '',
      };
      this.dateTime = []
      this.$refs.multipleTable.clearSelection();
      this.handleList();
    },

    handleBatch() {
      console.log(this.returnCategoryList)
      let booleA = this.returnCategoryList.every(a => a === '5')  //都是5
      let booleB = this.returnCategoryList.every(a => a !== '5')  //不含5
      let booleC = booleA || booleB
      console.log(booleA, booleB, booleC, "-=-==-")
      if ((new Set(this.orderNoList).size === 1) && booleC) {
        this._toPage({
          path: "/ReturnCar/ReturnMarginMerge",
          name: "ReturnMarginMerge",
          query: {
            id: this.idList,
            type: 'edit'
          }
        });
      } else {
        let msg
        booleC ? msg = '相同主订单的车辆订单可合并退保' : msg = '还车类别包含合同变更还车(同一批次都是合同变更还车可合并退保)'
        this.$message.warning(msg)
      }
    },

    handleDerive() {
      this.download_json(
          "/returnCarDeposit/export",
          {...this.queryParams},
          `退保证金_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped lang=""></style>


